3 * Implements Special:Block
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
24 use MediaWiki\Block\BlockRestriction
;
25 use MediaWiki\Block\Restriction\PageRestriction
;
26 use MediaWiki\Block\Restriction\NamespaceRestriction
;
29 * A special page that allows users with 'block' right to block users from
30 * editing pages and other actions
32 * @ingroup SpecialPage
34 class SpecialBlock
extends FormSpecialPage
{
35 /** @var User|string|null User to be blocked, as passed either by parameter (url?wpTarget=Foo)
36 * or as subpage (Special:Block/Foo) */
39 /** @var int Block::TYPE_ constant */
42 /** @var User|string The previous block target */
43 protected $previousTarget;
45 /** @var bool Whether the previous submission of the form asked for HideUser */
46 protected $requestedHideUser;
49 protected $alreadyBlocked;
52 protected $preErrors = [];
54 public function __construct() {
55 parent
::__construct( 'Block', 'block' );
58 public function doesWrites() {
63 * Checks that the user can unblock themselves if they are trying to do so
66 * @throws ErrorPageError
68 protected function checkExecutePermissions( User
$user ) {
69 parent
::checkExecutePermissions( $user );
70 # T17810: blocked admins should have limited access here
71 $status = self
::checkUnblockSelf( $this->target
, $user );
72 if ( $status !== true ) {
73 throw new ErrorPageError( 'badaccess', $status );
78 * We allow certain special cases where user is blocked
82 public function requiresUnblock() {
87 * Handle some magic here
91 protected function setParameter( $par ) {
92 # Extract variables from the request. Try not to get into a situation where we
93 # need to extract *every* variable from the form just for processing here, but
94 # there are legitimate uses for some variables
95 $request = $this->getRequest();
96 list( $this->target
, $this->type
) = self
::getTargetAndType( $par, $request );
97 if ( $this->target
instanceof User
) {
98 # Set the 'relevant user' in the skin, so it displays links like Contributions,
99 # User logs, UserRights, etc.
100 $this->getSkin()->setRelevantUser( $this->target
);
103 list( $this->previousTarget
, /*...*/ ) =
104 Block
::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
105 $this->requestedHideUser
= $request->getBool( 'wpHideUser' );
109 * Customizes the HTMLForm a bit
111 * @param HTMLForm $form
113 protected function alterForm( HTMLForm
$form ) {
114 $form->setHeaderText( '' );
115 $form->setSubmitDestructive();
117 $msg = $this->alreadyBlocked ?
'ipb-change-block' : 'ipbsubmit';
118 $form->setSubmitTextMsg( $msg );
120 $this->addHelpLink( 'Help:Blocking users' );
122 # Don't need to do anything if the form has been posted
123 if ( !$this->getRequest()->wasPosted() && $this->preErrors
) {
124 $s = $form->formatErrors( $this->preErrors
);
126 $form->addHeaderText( Html
::rawElement(
128 [ 'class' => 'error' ],
135 protected function getDisplayFormat() {
140 * Get the HTMLForm descriptor array for the block form
143 protected function getFormFields() {
144 global $wgBlockAllowsUTEdit;
146 $this->getOutput()->enableOOUI();
148 $user = $this->getUser();
150 $suggestedDurations = self
::getSuggestedDurations();
152 $conf = $this->getConfig();
153 $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
161 'id' => 'mw-bi-target',
165 'validation-callback' => [ __CLASS__
, 'validateTargetField' ],
166 'section' => 'target',
171 'label-message' => 'block-prevent-edit',
173 'section' => 'actions',
174 'disabled' => $enablePartialBlocks ?
false : true,
177 if ( $enablePartialBlocks ) {
178 $a['EditingRestriction'] = [
180 'cssclass' => 'mw-block-editing-restriction',
182 $this->msg( 'ipb-sitewide' )->escaped() .
183 new \OOUI\
LabelWidget( [
184 'classes' => [ 'oo-ui-inline-help' ],
185 'label' => $this->msg( 'ipb-sitewide-help' )->text(),
187 $this->msg( 'ipb-partial' )->escaped() .
188 new \OOUI\
LabelWidget( [
189 'classes' => [ 'oo-ui-inline-help' ],
190 'label' => $this->msg( 'ipb-partial-help' )->text(),
193 'section' => 'actions',
195 $a['PageRestrictions'] = [
196 'type' => 'titlesmultiselect',
197 'label' => $this->msg( 'ipb-pages-label' )->text(),
200 'cssclass' => 'mw-block-restriction',
201 'showMissing' => false,
202 'excludeDynamicNamespaces' => true,
204 'autocomplete' => false
206 'section' => 'actions',
208 $a['NamespaceRestrictions'] = [
209 'type' => 'namespacesmultiselect',
210 'label' => $this->msg( 'ipb-namespaces-label' )->text(),
212 'cssclass' => 'mw-block-restriction',
214 'autocomplete' => false
216 'section' => 'actions',
220 $a['CreateAccount'] = [
222 'label-message' => 'ipbcreateaccount',
224 'section' => 'actions',
227 if ( self
::canBlockEmail( $user ) ) {
228 $a['DisableEmail'] = [
230 'label-message' => 'ipbemailban',
231 'section' => 'actions',
235 if ( $wgBlockAllowsUTEdit ) {
236 $a['DisableUTEdit'] = [
238 'label-message' => 'ipb-disableusertalk',
240 'section' => 'actions',
247 'options' => $suggestedDurations,
248 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
249 'section' => 'expiry',
253 'type' => 'selectandother',
254 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
255 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
256 // Unicode codepoints.
257 'maxlength' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
258 'maxlength-unit' => 'codepoints',
259 'options-message' => 'ipbreason-dropdown',
260 'section' => 'reason',
265 'label-message' => 'ipbenableautoblock',
267 'section' => 'options',
270 # Allow some users to hide name from block log, blocklist and listusers
271 if ( $user->isAllowed( 'hideuser' ) ) {
274 'label-message' => 'ipbhidename',
275 'cssclass' => 'mw-block-hideuser',
276 'section' => 'options',
280 # Watchlist their user page? (Only if user is logged in)
281 if ( $user->isLoggedIn() ) {
284 'label-message' => 'ipbwatchuser',
285 'section' => 'options',
291 'label-message' => 'ipb-hardblock',
293 'section' => 'options',
296 # This is basically a copy of the Target field, but the user can't change it, so we
297 # can see if the warnings we maybe showed to the user before still apply
298 $a['PreviousTarget'] = [
303 # We'll turn this into a checkbox if we need to
307 'label-message' => 'ipb-confirm',
308 'cssclass' => 'mw-block-confirm',
311 // Block Id if a block already exists matching the target
317 // Has the form been submitted
323 $this->maybeAlterFormDefaults( $a );
325 // Allow extensions to add more fields
326 Hooks
::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
332 * If the user has already been blocked with similar settings, load that block
333 * and change the defaults for the form fields to match the existing settings.
334 * @param array &$fields HTMLForm descriptor array
336 protected function maybeAlterFormDefaults( &$fields ) {
337 # This will be overwritten by request data
338 $fields['Target']['default'] = (string)$this->target
;
340 if ( $this->target
) {
341 $status = self
::validateTarget( $this->target
, $this->getUser() );
342 if ( !$status->isOK() ) {
343 $errors = $status->getErrorsArray();
344 $this->preErrors
= array_merge( $this->preErrors
, $errors );
349 $fields['PreviousTarget']['default'] = (string)$this->target
;
351 $block = Block
::newFromTarget( $this->target
);
353 // Populate fields if there is a block that is not an autoblock; if it is a range
354 // block, only populate the fields if the range is the same as $this->target
355 if ( $block instanceof Block
&& $block->getType() !== Block
::TYPE_AUTO
356 && ( $this->type
!= Block
::TYPE_RANGE
357 ||
$block->getTarget() == $this->target
)
359 $fields['HardBlock']['default'] = $block->isHardblock();
360 $fields['CreateAccount']['default'] = $block->isCreateAccountBlocked();
361 $fields['AutoBlock']['default'] = $block->isAutoblocking();
363 if ( isset( $fields['DisableEmail'] ) ) {
364 $fields['DisableEmail']['default'] = $block->isEmailBlocked();
367 if ( isset( $fields['HideUser'] ) ) {
368 $fields['HideUser']['default'] = $block->getHideName();
371 if ( isset( $fields['DisableUTEdit'] ) ) {
372 $fields['DisableUTEdit']['default'] = !$block->isUsertalkEditAllowed();
375 // If the username was hidden (ipb_deleted == 1), don't show the reason
376 // unless this user also has rights to hideuser: T37839
377 if ( !$block->getHideName() ||
$this->getUser()->isAllowed( 'hideuser' ) ) {
378 $fields['Reason']['default'] = $block->getReason();
380 $fields['Reason']['default'] = '';
383 if ( $this->getRequest()->wasPosted() ) {
384 # Ok, so we got a POST submission asking us to reblock a user. So show the
385 # confirm checkbox; the user will only see it if they haven't previously
386 $fields['Confirm']['type'] = 'check';
388 # We got a target, but it wasn't a POST request, so the user must have gone
389 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
390 # as long as they go ahead and block *that* user
391 $fields['Confirm']['default'] = 1;
394 if ( $block->getExpiry() == 'infinity' ) {
395 $fields['Expiry']['default'] = 'infinite';
397 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->getExpiry() );
400 $fields['BlockId']['default'] = $block->getId();
402 $this->alreadyBlocked
= true;
403 $this->preErrors
[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
406 if ( $this->getRequest()->wasPosted() ) {
407 $fields['WasPosted']['default'] = true;
410 # We always need confirmation to do HideUser
411 if ( $this->requestedHideUser
) {
412 $fields['Confirm']['type'] = 'check';
413 unset( $fields['Confirm']['default'] );
414 $this->preErrors
[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
417 # Or if the user is trying to block themselves
418 if ( (string)$this->target
=== $this->getUser()->getName() ) {
419 $fields['Confirm']['type'] = 'check';
420 unset( $fields['Confirm']['default'] );
421 $this->preErrors
[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
424 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
425 if ( $block instanceof Block
&& !$block->isSitewide() ) {
426 $fields['EditingRestriction']['default'] = 'partial';
428 $fields['EditingRestriction']['default'] = 'sitewide';
431 if ( $block instanceof Block
) {
432 $pageRestrictions = [];
433 $namespaceRestrictions = [];
434 foreach ( $block->getRestrictions() as $restriction ) {
435 switch ( $restriction->getType() ) {
436 case PageRestriction
::TYPE
:
437 if ( $restriction->getTitle() ) {
438 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
441 case NamespaceRestriction
::TYPE
:
442 $namespaceRestrictions[] = $restriction->getValue();
448 !$block->isSitewide() &&
449 empty( $pageRestrictions ) &&
450 empty( $namespaceRestrictions )
452 $fields['Editing']['default'] = false;
455 // Sort the restrictions so they are in alphabetical order.
456 sort( $pageRestrictions );
457 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
458 sort( $namespaceRestrictions );
459 $fields['NamespaceRestrictions']['default'] = implode( "\n", $namespaceRestrictions );
465 * Add header elements like block log entries, etc.
468 protected function preText() {
469 $this->getOutput()->addModuleStyles( [
470 'mediawiki.widgets.TagMultiselectWidget.styles',
473 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
475 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
476 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
478 $otherBlockMessages = [];
479 if ( $this->target
!== null ) {
480 $targetName = $this->target
;
481 if ( $this->target
instanceof User
) {
482 $targetName = $this->target
->getName();
484 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
485 Hooks
::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
487 if ( count( $otherBlockMessages ) ) {
488 $s = Html
::rawElement(
491 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
496 foreach ( $otherBlockMessages as $link ) {
497 $list .= Html
::rawElement( 'li', [], $link ) . "\n";
500 $s .= Html
::rawElement(
502 [ 'class' => 'mw-blockip-alreadyblocked' ],
514 * Add footer elements to the form
517 protected function postText() {
520 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
522 $linkRenderer = $this->getLinkRenderer();
523 # Link to the user's contributions, if applicable
524 if ( $this->target
instanceof User
) {
525 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
526 $links[] = $linkRenderer->makeLink(
528 $this->msg( 'ipb-blocklist-contribs', $this->target
->getName() )->text()
532 # Link to unblock the specified user, or to a blank unblock form
533 if ( $this->target
instanceof User
) {
534 $message = $this->msg(
536 wfEscapeWikiText( $this->target
->getName() )
538 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
540 $message = $this->msg( 'ipb-unblock' )->parse();
541 $list = SpecialPage
::getTitleFor( 'Unblock' );
543 $links[] = $linkRenderer->makeKnownLink(
545 new HtmlArmor( $message )
548 # Link to the block list
549 $links[] = $linkRenderer->makeKnownLink(
550 SpecialPage
::getTitleFor( 'BlockList' ),
551 $this->msg( 'ipb-blocklist' )->text()
554 $user = $this->getUser();
556 # Link to edit the block dropdown reasons, if applicable
557 if ( $user->isAllowed( 'editinterface' ) ) {
558 $links[] = $linkRenderer->makeKnownLink(
559 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
560 $this->msg( 'ipb-edit-dropdown' )->text(),
562 [ 'action' => 'edit' ]
566 $text = Html
::rawElement(
568 [ 'class' => 'mw-ipb-conveniencelinks' ],
569 $this->getLanguage()->pipeList( $links )
572 $userTitle = self
::getTargetUserTitle( $this->target
);
574 # Get relevant extracts from the block and suppression logs, if possible
577 LogEventsList
::showLogExtract(
584 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
585 'showIfEmpty' => false
590 # Add suppression block entries if allowed
591 if ( $user->isAllowed( 'suppressionlog' ) ) {
592 LogEventsList
::showLogExtract(
599 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
600 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
601 'showIfEmpty' => false
613 * Get a user page target for things like logs.
614 * This handles account and IP range targets.
615 * @param User|string $target
618 protected static function getTargetUserTitle( $target ) {
619 if ( $target instanceof User
) {
620 return $target->getUserPage();
621 } elseif ( IP
::isIPAddress( $target ) ) {
622 return Title
::makeTitleSafe( NS_USER
, $target );
629 * Determine the target of the block, and the type of target
630 * @todo Should be in Block.php?
631 * @param string $par Subpage parameter passed to setup, or data value from
633 * @param WebRequest|null $request Optionally try and get data from a request too
634 * @return array [ User|string|null, Block::TYPE_ constant|null ]
636 public static function getTargetAndType( $par, WebRequest
$request = null ) {
643 # The HTMLForm will check wpTarget first and only if it doesn't get
644 # a value use the default, which will be generated from the options
645 # below; so this has to have a higher precedence here than $par, or
646 # we could end up with different values in $this->target and the HTMLForm!
647 if ( $request instanceof WebRequest
) {
648 $target = $request->getText( 'wpTarget', null );
655 if ( $request instanceof WebRequest
) {
656 $target = $request->getText( 'ip', null );
661 if ( $request instanceof WebRequest
) {
662 $target = $request->getText( 'wpBlockAddress', null );
669 list( $target, $type ) = Block
::parseTarget( $target );
671 if ( $type !== null ) {
672 return [ $target, $type ];
676 return [ null, null ];
680 * HTMLForm field validation-callback for Target field.
682 * @param string $value
683 * @param array $alldata
684 * @param HTMLForm $form
687 public static function validateTargetField( $value, $alldata, $form ) {
688 $status = self
::validateTarget( $value, $form->getUser() );
689 if ( !$status->isOK() ) {
690 $errors = $status->getErrorsArray();
692 return $form->msg( ...$errors[0] );
699 * Validate a block target.
702 * @param string $value Block target to check
703 * @param User $user Performer of the block
706 public static function validateTarget( $value, User
$user ) {
707 global $wgBlockCIDRLimit;
709 /** @var User $target */
710 list( $target, $type ) = self
::getTargetAndType( $value );
711 $status = Status
::newGood( $target );
713 if ( $type == Block
::TYPE_USER
) {
714 if ( $target->isAnon() ) {
717 wfEscapeWikiText( $target->getName() )
721 $unblockStatus = self
::checkUnblockSelf( $target, $user );
722 if ( $unblockStatus !== true ) {
723 $status->fatal( 'badaccess', $unblockStatus );
725 } elseif ( $type == Block
::TYPE_RANGE
) {
726 list( $ip, $range ) = explode( '/', $target, 2 );
729 ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
730 ( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
732 // Range block effectively disabled
733 $status->fatal( 'range_block_disabled' );
737 ( IP
::isIPv4( $ip ) && $range > 32 ) ||
738 ( IP
::isIPv6( $ip ) && $range > 128 )
741 $status->fatal( 'ip_range_invalid' );
744 if ( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
745 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
748 if ( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
749 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
751 } elseif ( $type == Block
::TYPE_IP
) {
754 $status->fatal( 'badipaddress' );
761 * Given the form data, actually implement a block. This is also called from ApiBlock.
764 * @param IContextSource $context
765 * @return bool|string
767 public static function processForm( array $data, IContextSource
$context ) {
768 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
770 $performer = $context->getUser();
771 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
772 $isPartialBlock = $enablePartialBlocks &&
773 isset( $data['EditingRestriction'] ) &&
774 $data['EditingRestriction'] === 'partial';
776 // Handled by field validator callback
777 // self::validateTargetField( $data['Target'] );
779 # This might have been a hidden field or a checkbox, so interesting data
781 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
783 /** @var User $target */
784 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
785 if ( $type == Block
::TYPE_USER
) {
787 $target = $user->getName();
788 $userId = $user->getId();
790 # Give admins a heads-up before they go and block themselves. Much messier
791 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
792 # permission anyway, although the code does allow for it.
793 # Note: Important to use $target instead of $data['Target']
794 # since both $data['PreviousTarget'] and $target are normalized
795 # but $data['target'] gets overridden by (non-normalized) request variable
796 # from previous request.
797 if ( $target === $performer->getName() &&
798 ( $data['PreviousTarget'] !== $target ||
!$data['Confirm'] )
800 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
802 } elseif ( $type == Block
::TYPE_RANGE
) {
805 } elseif ( $type == Block
::TYPE_IP
) {
807 $target = $target->getName();
810 # This should have been caught in the form field validation
811 return [ 'badipaddress' ];
814 $expiryTime = self
::parseExpiryInput( $data['Expiry'] );
817 // an expiry time is needed
818 ( strlen( $data['Expiry'] ) == 0 ) ||
819 // can't be a larger string as 50 (it should be a time format in any way)
820 ( strlen( $data['Expiry'] ) > 50 ) ||
821 // check, if the time could be parsed
824 return [ 'ipb_expiry_invalid' ];
827 // an expiry time should be in the future, not in the
828 // past (wouldn't make any sense) - bug T123069
829 if ( $expiryTime < wfTimestampNow() ) {
830 return [ 'ipb_expiry_old' ];
833 if ( !isset( $data['DisableEmail'] ) ) {
834 $data['DisableEmail'] = false;
837 # If the user has done the form 'properly', they won't even have been given the
838 # option to suppress-block unless they have the 'hideuser' permission
839 if ( !isset( $data['HideUser'] ) ) {
840 $data['HideUser'] = false;
843 if ( $data['HideUser'] ) {
844 if ( !$performer->isAllowed( 'hideuser' ) ) {
845 # this codepath is unreachable except by a malicious user spoofing forms,
846 # or by race conditions (user has hideuser and block rights, loads block form,
847 # and loses hideuser rights before submission); so need to fail completely
848 # rather than just silently disable hiding
849 return [ 'badaccess-group0' ];
852 if ( $isPartialBlock ) {
853 return [ 'ipb_hide_partial' ];
856 # Recheck params here...
857 if ( $type != Block
::TYPE_USER
) {
858 $data['HideUser'] = false; # IP users should not be hidden
859 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
861 return [ 'ipb_expiry_temp' ];
862 } elseif ( $wgHideUserContribLimit !== false
863 && $user->getEditCount() > $wgHideUserContribLimit
865 # Typically, the user should have a handful of edits.
866 # Disallow hiding users with many edits for performance.
867 return [ [ 'ipb_hide_invalid',
868 Message
::numParam( $wgHideUserContribLimit ) ] ];
869 } elseif ( !$data['Confirm'] ) {
870 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
874 # Create block object.
875 $block = new Block();
876 $block->setTarget( $target );
877 $block->setBlocker( $performer );
878 $block->setReason( $data['Reason'][0] );
879 $block->setExpiry( $expiryTime );
880 $block->isCreateAccountBlocked( $data['CreateAccount'] );
881 $block->isUsertalkEditAllowed( !$wgBlockAllowsUTEdit ||
!$data['DisableUTEdit'] );
882 $block->isEmailBlocked( $data['DisableEmail'] );
883 $block->isHardblock( $data['HardBlock'] );
884 $block->isAutoblocking( $data['AutoBlock'] );
885 $block->setHideName( $data['HideUser'] );
887 if ( $isPartialBlock ) {
888 $block->isSitewide( false );
891 $reason = [ 'hookaborted' ];
892 if ( !Hooks
::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
896 $pageRestrictions = [];
897 $namespaceRestrictions = [];
898 if ( $enablePartialBlocks ) {
899 if ( $data['PageRestrictions'] !== '' ) {
900 $pageRestrictions = array_map( function ( $text ) {
901 $title = Title
::newFromText( $text );
902 // Use the link cache since the title has already been loaded when
903 // the field was validated.
904 $restriction = new PageRestriction( 0, $title->getArticleID() );
905 $restriction->setTitle( $title );
907 }, explode( "\n", $data['PageRestrictions'] ) );
909 if ( $data['NamespaceRestrictions'] !== '' ) {
910 $namespaceRestrictions = array_map( function ( $id ) {
911 return new NamespaceRestriction( 0, $id );
912 }, explode( "\n", $data['NamespaceRestrictions'] ) );
915 $restrictions = ( array_merge( $pageRestrictions, $namespaceRestrictions ) );
916 $block->setRestrictions( $restrictions );
920 # Try to insert block. Is there a conflicting block?
921 $status = $block->insert();
923 # Indicates whether the user is confirming the block and is aware of
924 # the conflict (did not change the block target in the meantime)
925 $blockNotConfirmed = !$data['Confirm'] ||
( array_key_exists( 'PreviousTarget', $data )
926 && $data['PreviousTarget'] !== $target );
928 # Special case for API - T34434
929 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
931 # Show form unless the user is already aware of this...
932 if ( $blockNotConfirmed ||
$reblockNotAllowed ) {
933 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
934 # Otherwise, try to update the block...
936 # This returns direct blocks before autoblocks/rangeblocks, since we should
937 # be sure the user is blocked by now it should work for our purposes
938 $currentBlock = Block
::newFromTarget( $target );
939 if ( $block->equals( $currentBlock ) ) {
940 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
942 # If the name was hidden and the blocking user cannot hide
943 # names, then don't allow any block changes...
944 if ( $currentBlock->getHideName() && !$performer->isAllowed( 'hideuser' ) ) {
945 return [ 'cant-see-hidden-user' ];
948 $priorBlock = clone $currentBlock;
949 $currentBlock->isHardblock( $block->isHardblock() );
950 $currentBlock->isCreateAccountBlocked( $block->isCreateAccountBlocked() );
951 $currentBlock->setExpiry( $block->getExpiry() );
952 $currentBlock->isAutoblocking( $block->isAutoblocking() );
953 $currentBlock->setHideName( $block->getHideName() );
954 $currentBlock->isEmailBlocked( $block->isEmailBlocked() );
955 $currentBlock->isUsertalkEditAllowed( $block->isUsertalkEditAllowed() );
956 $currentBlock->setReason( $block->getReason() );
958 if ( $enablePartialBlocks ) {
959 // Maintain the sitewide status. If partial blocks is not enabled,
960 // saving the block will result in a sitewide block.
961 $currentBlock->isSitewide( $block->isSitewide() );
963 // Set the block id of the restrictions.
964 $currentBlock->setRestrictions(
965 BlockRestriction
::setBlockId( $currentBlock->getId(), $restrictions )
969 $status = $currentBlock->update();
970 // TODO handle failure
972 $logaction = 'reblock';
974 # Unset _deleted fields if requested
975 if ( $currentBlock->getHideName() && !$data['HideUser'] ) {
976 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
979 # If hiding/unhiding a name, this should go in the private logs
980 if ( (bool)$currentBlock->getHideName() ) {
981 $data['HideUser'] = true;
984 $block = $currentBlock;
987 $logaction = 'block';
990 Hooks
::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
992 # Set *_deleted fields if requested
993 if ( $data['HideUser'] ) {
994 RevisionDeleteUser
::suppressUserName( $target, $userId );
997 # Can't watch a rangeblock
998 if ( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
999 WatchAction
::doWatch(
1000 Title
::makeTitle( NS_USER
, $target ),
1002 User
::IGNORE_USER_RIGHTS
1006 # Block constructor sanitizes certain block options on insert
1007 $data['BlockEmail'] = $block->isEmailBlocked();
1008 $data['AutoBlock'] = $block->isAutoblocking();
1010 # Prepare log parameters
1012 $logParams['5::duration'] = $data['Expiry'];
1013 $logParams['6::flags'] = self
::blockLogFlags( $data, $type );
1014 $logParams['sitewide'] = $block->isSitewide();
1016 if ( $enablePartialBlocks && !$block->isSitewide() ) {
1017 if ( $data['PageRestrictions'] !== '' ) {
1018 $logParams['7::restrictions']['pages'] = explode( "\n", $data['PageRestrictions'] );
1021 if ( $data['NamespaceRestrictions'] !== '' ) {
1022 $logParams['7::restrictions']['namespaces'] = explode( "\n", $data['NamespaceRestrictions'] );
1026 # Make log entry, if the name is hidden, put it in the suppression log
1027 $log_type = $data['HideUser'] ?
'suppress' : 'block';
1028 $logEntry = new ManualLogEntry( $log_type, $logaction );
1029 $logEntry->setTarget( Title
::makeTitle( NS_USER
, $target ) );
1030 $logEntry->setComment( $data['Reason'][0] );
1031 $logEntry->setPerformer( $performer );
1032 $logEntry->setParameters( $logParams );
1033 # Relate log ID to block ID (T27763)
1034 $logEntry->setRelations( [ 'ipb_id' => $block->getId() ] );
1035 $logId = $logEntry->insert();
1037 if ( !empty( $data['Tags'] ) ) {
1038 $logEntry->setTags( $data['Tags'] );
1041 $logEntry->publish( $logId );
1047 * Get an array of suggested block durations from MediaWiki:Ipboptions
1048 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
1049 * to the standard "**<duration>|<displayname>" format?
1050 * @param Language|null $lang The language to get the durations in, or null to use
1051 * the wiki's content language
1052 * @param bool $includeOther Whether to include the 'other' option in the list of
1056 public static function getSuggestedDurations( Language
$lang = null, $includeOther = true ) {
1058 $msg = $lang === null
1059 ?
wfMessage( 'ipboptions' )->inContentLanguage()->text()
1060 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
1062 if ( $msg == '-' ) {
1066 foreach ( explode( ',', $msg ) as $option ) {
1067 if ( strpos( $option, ':' ) === false ) {
1068 $option = "$option:$option";
1071 list( $show, $value ) = explode( ':', $option );
1075 if ( $a && $includeOther ) {
1076 // if options exist, add other to the end instead of the begining (which
1077 // is what happens by default).
1078 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
1085 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1086 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
1088 * @todo strtotime() only accepts English strings. This means the expiry input
1089 * can only be specified in English.
1090 * @see https://secure.php.net/manual/en/function.strtotime.php
1092 * @param string $expiry Whatever was typed into the form
1093 * @return string|bool Timestamp or 'infinity' or false on error.
1095 public static function parseExpiryInput( $expiry ) {
1096 if ( wfIsInfinity( $expiry ) ) {
1100 $expiry = strtotime( $expiry );
1102 if ( $expiry < 0 ||
$expiry === false ) {
1106 return wfTimestamp( TS_MW
, $expiry );
1110 * Can we do an email block?
1111 * @param User $user The sysop wanting to make a block
1114 public static function canBlockEmail( $user ) {
1115 global $wgEnableUserEmail, $wgSysopEmailBans;
1117 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1121 * T17810: blocked admins should not be able to block/unblock
1122 * others, and probably shouldn't be able to unblock themselves
1125 * Exception: Users can block the user who blocked them, to reduce
1126 * advantage of a malicious account blocking all admins (T150826)
1128 * @param User|int|string|null $target Target to block or unblock; could be a User object,
1129 * or a user ID or username, or null when the target is not known yet (e.g. when
1130 * displaying Special:Block)
1131 * @param User $performer User doing the request
1132 * @return bool|string True or error message key
1134 public static function checkUnblockSelf( $target, User
$performer ) {
1135 if ( is_int( $target ) ) {
1136 $target = User
::newFromId( $target );
1137 } elseif ( is_string( $target ) ) {
1138 $target = User
::newFromName( $target );
1140 if ( $performer->isBlocked() ) {
1141 if ( $target instanceof User
&& $target->getId() == $performer->getId() ) {
1142 # User is trying to unblock themselves
1143 if ( $performer->isAllowed( 'unblockself' ) ) {
1145 # User blocked themselves and is now trying to reverse it
1146 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1149 return 'ipbnounblockself';
1152 $target instanceof User
&&
1153 $performer->getBlock() instanceof Block
&&
1154 $performer->getBlock()->getBy() &&
1155 $performer->getBlock()->getBy() === $target->getId()
1157 // Allow users to block the user that blocked them.
1158 // This is to prevent a situation where a malicious user
1159 // blocks all other users. This way, the non-malicious
1160 // user can block the malicious user back, resulting
1165 # User is trying to block/unblock someone else
1166 return 'ipbblocked';
1174 * Return a comma-delimited list of "flags" to be passed to the log
1175 * reader for this block, to provide more information in the logs
1176 * @param array $data From HTMLForm data
1177 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1180 protected static function blockLogFlags( array $data, $type ) {
1181 $config = RequestContext
::getMain()->getConfig();
1183 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1187 # when blocking a user the option 'anononly' is not available/has no effect
1188 # -> do not write this into log
1189 if ( !$data['HardBlock'] && $type != Block
::TYPE_USER
) {
1190 // For grepping: message block-log-flags-anononly
1191 $flags[] = 'anononly';
1194 if ( $data['CreateAccount'] ) {
1195 // For grepping: message block-log-flags-nocreate
1196 $flags[] = 'nocreate';
1199 # Same as anononly, this is not displayed when blocking an IP address
1200 if ( !$data['AutoBlock'] && $type == Block
::TYPE_USER
) {
1201 // For grepping: message block-log-flags-noautoblock
1202 $flags[] = 'noautoblock';
1205 if ( $data['DisableEmail'] ) {
1206 // For grepping: message block-log-flags-noemail
1207 $flags[] = 'noemail';
1210 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1211 // For grepping: message block-log-flags-nousertalk
1212 $flags[] = 'nousertalk';
1215 if ( $data['HideUser'] ) {
1216 // For grepping: message block-log-flags-hiddenname
1217 $flags[] = 'hiddenname';
1220 return implode( ',', $flags );
1224 * Process the form on POST submission.
1225 * @param array $data
1226 * @param HTMLForm|null $form
1227 * @return bool|array True for success, false for didn't-try, array of errors on failure
1229 public function onSubmit( array $data, HTMLForm
$form = null ) {
1230 // If "Editing" checkbox is unchecked, the block must be a partial block affecting
1231 // actions other than editing, and there must be no restrictions.
1232 if ( isset( $data['Editing'] ) && $data['Editing'] === false ) {
1233 $data['EditingRestriction'] = 'partial';
1234 $data['PageRestrictions'] = '';
1235 $data['NamespaceRestrictions'] = '';
1237 return self
::processForm( $data, $form->getContext() );
1241 * Do something exciting on successful processing of the form, most likely to show a
1242 * confirmation message
1244 public function onSuccess() {
1245 $out = $this->getOutput();
1246 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1247 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target
) );
1251 * Return an array of subpages beginning with $search that this special page will accept.
1253 * @param string $search Prefix to search for
1254 * @param int $limit Maximum number of results to return (usually 10)
1255 * @param int $offset Number of results to skip (usually 0)
1256 * @return string[] Matching subpages
1258 public function prefixSearchSubpages( $search, $limit, $offset ) {
1259 $user = User
::newFromName( $search );
1261 // No prefix suggestion for invalid user
1264 // Autocomplete subpage as user list - public to allow caching
1265 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
1268 protected function getGroupName() {